package com.heima.wemedia.message;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.heima.common.contants.MessageConstants;
import com.heima.wemedia.service.WmNewsService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ScanResultMessageListener {
    @Autowired
    private WmNewsService wmNewsService;

    /**
     * 交换机：NEWS_SCAN_RESULT_QUEUE = "scan.news.result.queue"
     * 队列：GREEN_SCAN_RESULT_EXCHANGE = "scan.result.exchange"
     * key：news
     * @param message
     */
    // 监听新闻扫描队列的消息
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MessageConstants.NEWS_SCAN_RESULT_QUEUE,durable = "true"),
            exchange = @Exchange(value = MessageConstants.GREEN_SCAN_RESULT_EXCHANGE,type = ExchangeTypes.DIRECT),
            key = MessageConstants.NEWS_SCAN_KEY
    ))
    /**
     * 监听扫描结果消息并更新新闻审核状态
     * 该方法用于处理接收到的扫描结果消息，并根据消息内容更新新闻的审核结果
     * 主要解决了如何高效地解析消息内容并更新到数据库的问题
     *
     * @param message 扫描结果消息，包含新闻ID、审核建议和原因
     * @throws Exception 如果消息解析或数据库更新过程中发生错误，则抛出异常
     */
    public void listenerScanResultMessage(String message) throws Exception {
        // 如果消息为空，则直接返回
        if (StrUtil.isEmpty(message)){
            return;
        }
        // 解析JSON消息
        JSONObject jsonObject = JSONUtil.parseObj(message);
        // 提取新闻ID
        Long newsId = jsonObject.getLong("newsId");
        // 提取审核建议
        String suggestion = jsonObject.getStr("suggestion");
        // 提取审核原因
        String reason = jsonObject.getStr("reason");
        // 调用服务层方法更新扫描结果
        wmNewsService.updateScanResult(newsId, suggestion,reason);
    }
}
